package service

import (
	"fmt"
	"rongyy/src/models"
)

type CompetitionService struct {
	d *models.CompetitionModel
}

func (ds *CompetitionService) Create(req *models.CompetitionModel) error {
	// 查询是否报价
	om := &models.OrdersModel{}
	order, has, err := om.FindByOrder(req.OrderSn)
	if err != nil {
		return err
	}
	if !has {
		return fmt.Errorf("订单不存在")
	}
	if order.Status != "pending" {
		return fmt.Errorf("订单状态错误")
	}
	cm := &models.CompetitionModel{
		OrderSn:    req.OrderSn,
		MerchantId: req.MerchantId,
	}
	_, has, err = cm.FindByOrderAndMerchant(req.OrderSn, req.MerchantId)
	if has {
		return fmt.Errorf("已报价")
	}
	err = req.Create()
	if err != nil {
		return err
	}
	return nil
}

func (ds *CompetitionService) QueryByOrder(req *models.ReqCompetitionQuery) ([]models.CompetitionModel, int64, error) {
	rm := &models.CompetitionModel{}
	data, total, err := rm.FindByOrder(req)
	if err != nil {
		return nil, 0, err
	}
	return data, total, nil
}

func (ds *CompetitionService) Accept(req *models.CompetitionModel) error {
	// 查询是否报价
	om := &models.OrdersModel{}
	order, has, err := om.FindByOrder(req.OrderSn)
	if err != nil {
		return err
	}
	if !has {
		return fmt.Errorf("订单不存在")
	}
	if order.Status != "pending" {
		return fmt.Errorf("订单状态错误")
	}
	cm := &models.CompetitionModel{
		OrderSn:    req.OrderSn,
		MerchantId: req.MerchantId,
	}
	reqFind := &models.ReqCompetitionQuery{
		OrderSn: req.OrderSn,
		Status:  "accept",
	}
	_, total, err := cm.FindByOrder(reqFind)
	if total > 0 {
		return fmt.Errorf("已经接受报价")
	}
	// 查询是否接受过报价
	err = cm.Accept(req)
	if err != nil {
		return err
	}
	om.OrderSn = req.OrderSn
	om.Status = "settled"
	err = om.UpdateStatus()
	if err != nil {
		return err
	}
	return nil
}
